
#include "hal_function.h"
#include "app_ui.h"

const static char *TAG = "Ui";
static AppUI *uiObj;
TaskHandle_t AppUI::taskHandle = NULL;
TimerHandle_t AppUI::timerHandle = NULL;
AppUI_LED::AppUI_LED()
{
    //set led mode with breath mode
    this->LED_Set(LED_MODE_BREATH,0);
}

void AppUI_LED::LED_Set(LED_MODE mode,int frequence)
{
   this->led_mode = mode;
   this->led_frequence = frequence;
   this->led_cnt = 0;
}

void AppUI_LED::LED_Run(int time)
{
   switch(this->led_mode)
   {
        case  LED_MODE_ON:
               pwm_set(0);
        break;
        case  LED_MODE_OFF:
               pwm_set(100);
        break;
        case  LED_MODE_FLASH:
               this->led_cnt+= time;
               if(this->led_cnt>=this->led_frequence)
               {
                  this->led_cnt = 0;
                  if(status)
                  {
                     pwm_set(0);
                  }
                  else
                  {
                      pwm_set(100);
                  }
                  status = !status;
               }
        break;
        case  LED_MODE_BREATH:
            if(this->breath_flag)
            {
               
               this->led_cnt += 1;
               if((this->led_cnt/UI_LED_DELAY)>= 100)
               {
                  this->breath_flag = 0;
               }
            }
            else
            {
               if(this->led_cnt == 0)
               {
                  this->breath_flag = 1;
               }
               else
               {
                  this->led_cnt -= 1;
               }
            }
            pwm_set(this->led_cnt/UI_LED_DELAY);
        break;
   }
}

AppUI::AppUI()
{
   
   
}



void AppUI::threadtimeCallback(TimerHandle_t handle)
{
   //button process
   uiObj->LED_Run(UI_TASK_TIME);
   lv_tick_inc(UI_TASK_TIME);
}

void AppUI::rootStyleInit()
{
   lv_obj_remove_style_all(lv_scr_act());
   lv_disp_set_bg_color(lv_disp_get_default(), lv_color_black());
}

void AppUI::thread(void *a)
{
   uiObj = new AppUI();
   lv_init();
   lv_port_disp_init();
   oledPubData.root_scr = lv_scr_act();
   AppUI::rootStyleInit();
   AppUI::timerHandle = xTimerCreate(TAG, pdMS_TO_TICKS(UI_TASK_TIME), true, NULL, AppUI::threadtimeCallback);
   xTimerStart(AppUI::timerHandle,pdMS_TO_TICKS(UI_TASK_TIME));
   while(1)
   {
      showOLED_Process(1);
      lv_task_handler();
      vTaskDelay(pdMS_TO_TICKS(UI_TASK_TIME)); 
   }
}


void AppUI::threadCreate()
{
   xTaskCreate(AppUI::thread, TAG, UI_STACK_SIZE, NULL, UI_TASK_PRIO, &(AppUI::taskHandle));
}
